#include "frame_thread_pool.h"

int threadPoolInit(threadPool_t *threadPool, int workerNum, MYSQL *mmysql) {
    tidArrInit(&threadPool->tidArr, workerNum);
    taskQueueInit(&threadPool->taskQueue);
    threadPool->exitFlag = 0;
    pthread_mutex_init(&threadPool->mutex, NULL);
    pthread_cond_init(&threadPool->cond, NULL);
    threadPool->mysql = mmysql;

    threadPool->ID = -1;
    memset(threadPool->userName, 0, sizeof(threadPool->userName));
    memset(threadPool->opName, 0, sizeof(threadPool->opName));
    
    threadPool->type = NOCOMMAND;

    return 0;
}

void threadPoolFree(threadPool_t *threadPool) {
    if (threadPool == NULL) {
        return;  // 防御性编程
    }

    // 1. 等待所有工作线程退出（需在外部join线程）
    // 注意：实际线程回收应在外部调用pthread_join完成

    // 2. 销毁同步原语
    pthread_mutex_destroy(&threadPool->mutex);
    pthread_cond_destroy(&threadPool->cond);

    // 3. 释放子模块资源
    tidArrFree(&threadPool->tidArr);    // 释放线程#include "directory_operation.h"
    taskQueueFree(&threadPool->taskQueue);  // 释放任务队列
}

int buildUserSpace() {
    if(access(userSpace, F_OK) != 0) {  
        mkdir(userSpace, 0777);
    } 
    return 1;
}

char* calculateSha1(const char* input) {
    if (input == NULL) {
        return NULL;
    }

    // 计算 SHA-1 哈希
    unsigned char hash[SHA_DIGEST_LENGTH]; // SHA_DIGEST_LENGTH = 20
    SHA1((const unsigned char*)input, strlen(input), hash);

    // 转换为 16 进制字符串
    char* hex_str = (char*)malloc(2 * SHA_DIGEST_LENGTH + 1); // 40字符 + '\0'
    if (hex_str == NULL) {
        return NULL; // 内存分配失败
    }

    for (int i = 0; i < SHA_DIGEST_LENGTH; i++) {
        sprintf(hex_str + 2 * i, "%02x", hash[i]);
    }
    hex_str[2 * SHA_DIGEST_LENGTH] = '\0';

    return hex_str;
}

int pathToId(MYSQL* mysql, char *path) {
    char sql[4096]={0};
    snprintf(sql,sizeof(sql),"select * from file_info where path ='%s'and type='d';",path);
    int sqlret=mysql_query(mysql,sql);
    if(sqlret!=0){
        fprintf(stderr,"%s:%s\n","pathToId mysql_query",mysql_error(mysql));
        exit(-1);
    }
    MYSQL_RES *res=mysql_store_result(mysql);
    MYSQL_ROW row=mysql_fetch_row(res);
    mysql_free_result(res);
    return atoi(row[0]);
}